/**
 * 
 */
package com.et114.modules.products.card.action;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.et114.components.simpletable.DataList;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.utility.FileUploadUtil;
import com.et114.core.utility.NumberUtils;
import com.et114.core.utility.StringPool;
import com.et114.core.utility.ThreadSynchronizer;
import com.et114.modules.products.commons.Const;
import com.et114.modules.products.commons.PorJsonObj;
import com.et114.modules.products.card.action.CardForm;
import com.et114.modules.products.card.services.CardServiceImpl;
import com.et114.modules.products.card.vo.Card;
import com.et114.modules.products.card.vo.CardServicePlan;
import com.et114.modules.products.card.vo.CardType;
import com.et114.modules.products.procontent.services.ProContentServiceImpl;
import com.et114.modules.products.procontent.vo.ProContent;
import com.et114.modules.products.supplier.services.SupplierServiceImpl;
import com.et114.modules.products.supplier.vo.ProSuppliers;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;

/*
 * @author guanhw
 *
 */
public class CardAction extends BaseDispatchAction {
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward getCard( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		long ct = System.currentTimeMillis ( ) ; 
		//DIC 
		List< BizOption >  bssOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_TYPE ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bssOps" , bssOps ) ;
		
		List< BizOption >  bsspOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_SERVICE_PLAN ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bsspOps" , bsspOps ) ;
		
		List< BizOption >  bproOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_PUB_STATUS_KEY ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bproOps" , bproOps ) ;
		
		
		SupplierServiceImpl ssbean = ( SupplierServiceImpl )getBean ( "supplierServiceImpl" ) ;
		ProSuppliers psvo = new ProSuppliers( ) ; 
		psvo.setSupplierPros ( StringPool.COMMA + Const.PRO_TYPE_CART + StringPool.COMMA ) ; 
		psvo.setWorkFlg ( String.valueOf ( Const.COMMON_STATUS_ENA ) ) ;
		List< ProSuppliers > proTypes = ssbean.querySuppliersList ( psvo ) ; 
		request.setAttribute ( "proTypes" , proTypes ) ;
		//BIS
		ProContentServiceImpl proContentServiceImpl = ( ProContentServiceImpl ) getBean ( "proContentServiceImpl" );
		CardServiceImpl sss = ( CardServiceImpl ) getBean ( "cardServiceImpl" );
		
		CardForm cardForm = ( CardForm ) form ; 
		Card card = new Card( ) ; 
		PropertyUtils.copyProperties ( card , cardForm ) ; 
		request.setAttribute ( "searchVo" , card ) ; 
		Long sdid = cardForm.getProId ( ) ; 
		if ( !NumberUtils.isEmptyOrZero ( sdid )  ) { // load one
			card = sss.getCardById (  sdid ) ; 
			//get content
			ProContent pcontent = proContentServiceImpl
					.getProContent ( new ProContent ( Byte
							.valueOf ( Const.PRO_TYPE_CART ) , sdid ) );
			if ( pcontent != null )
				request.setAttribute ( "content" , pcontent );

			request.setAttribute ( "card" , card ) ;
			return mapping.findForward ( "card" ) ; 
		}
		else { //loads
			DataList dl = sss.getCards ( card )  ; 
			List< Card > cards =  dl.getNowlist ( ) ;
			CardType cardTypeVo = null;
			CardServicePlan cardServicePlanv = null;
			for ( Card cardTmp : cards ) {
				cardTmp.setCardTypev ( null ) ; 
				cardTmp.setCardServicePlanv ( null ) ; 
				for ( BizOption bioCt : bssOps ) {
					if ( Byte.valueOf ( bioCt.getOptionValue ( ) ) .equals ( 
							cardTmp.getCardType ( ) ) ) {
						cardTypeVo = new CardType ( );
						cardTypeVo.setCardTypeId ( Byte.valueOf ( bioCt
								.getOptionValue ( ) ) );
						cardTypeVo.setCardTypeName ( bioCt.getOptionName ( ) );
						cardTmp.setCardTypev ( cardTypeVo );
						break;
					}
				}
				
				for ( BizOption bizop : bsspOps ) {
					if (  Byte.valueOf (  bizop.getOptionValue ( ) ) .equals ( 
							cardTmp.getCardPlan ( ) ) ) {
						cardServicePlanv = new CardServicePlan ( );
						cardServicePlanv.setCardServicePlanId ( Byte
								.valueOf ( bizop.getOptionValue ( ) ) );
						cardServicePlanv.setCardServicePlanName ( bizop
								.getOptionName ( ) );
						cardTmp.setCardServicePlanv ( cardServicePlanv );
						break;
					}
				}
			}
			
			logger.info ( "load card time:" + ( System.currentTimeMillis ( ) - ct ) ) ;
			request.setAttribute ( "dl" , dl ) ; 
			return mapping.findForward ( "cards" ) ; 
		}
		
	}
	
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward toEditCard ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC 
		List< BizOption >  bssOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_TYPE ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bssOps" , bssOps ) ;
		
		List< BizOption >  bsspOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_SERVICE_PLAN ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bsspOps" , bsspOps ) ;
		
		List< BizOption >  bproOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_PUB_STATUS_KEY ,  false  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "bproOps" , bproOps ) ;
		
		SupplierServiceImpl ssbean = ( SupplierServiceImpl )getBean ( "supplierServiceImpl" ) ;
		ProSuppliers psvo = new ProSuppliers( ) ; 
		psvo.setWorkFlg ( String.valueOf ( Const.COMMON_STATUS_ENA ) ) ;
		psvo.setSupplierPros ( StringPool.COMMA + Const.PRO_TYPE_CART + StringPool.COMMA ) ; 
		List< ProSuppliers > proTypes = ssbean.querySuppliersList ( psvo ) ; 
		request.setAttribute ( "proTypes" , proTypes ) ;
		
		return mapping.findForward ( "card" ) ; 
	}
	
	
	
	public  ActionForward editCard( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		CardForm cardForm = ( CardForm ) form ; 
		//DIC
		
		//PARAMS 
		
		//BIS
		CardServiceImpl sss = ( CardServiceImpl )getBean ( "cardServiceImpl" ) ;
		ProContentServiceImpl proContentServiceImpl = ( ProContentServiceImpl ) getBean ( "proContentServiceImpl" );
		
		Card card = new Card( ) ; 
		PropertyUtils.copyProperties ( card , cardForm ) ; 
		
		card.setUpdtUser ( getCurrentUser ( request ).getUserId ( ) ) ;
		Long id = cardForm.getProId ( ) ; 
		
		Byte actStatus = cardForm.getProActStatus ( ) ; 
		if (actStatus != null ) {
			if ( Const.PRO_ACTION_SUB == actStatus ) {
				if ( NumberUtils.isEmptyOrZero ( id ) )
					card.setCrtUser ( getCurrentUser ( request ).getUserId ( ) );
				id = saveAndUpdateCard ( card , cardForm.getCardImgff ( ) ,
						sss , request );
			}
			else if ( Const.PRO_ACTION_PUB == actStatus ) {
				card = sss.getCardById ( id ) ; 
				card.setProOnOffStatus ( Const.PRO_PUB_STATUS_PUBED ) ; 
				id = saveAndUpdateCard( card , cardForm.getCardImgff ( ) ,  sss , request ) ; 
			}
			else if ( Const.PRO_ACTION_SUB_CHECK == actStatus ) {
				card = sss.getCardById ( id ) ; 
				Date offTime = cardForm.getOffTime ( ) ; 
				if (  ( offTime != null && ( new Date ( )
								.getTime ( )- offTime.getTime ( ) >= 0 ) ) ) 			
					return PorJsonObj.response ( response , PorJsonObj.error ( "offTime" ) );				

				return PorJsonObj.response ( response , PorJsonObj.success (  "!" ) );	
			}
			else if ( Const.PRO_ACTION_SUB_PUB == actStatus ) {
				card.setProOnOffStatus ( Const.PRO_PUB_STATUS_PUBED );
				if ( id != null && id.longValue ( ) != 0 )
					saveAndUpdateCard ( card , cardForm.getCardImgff ( ) ,  sss , request  );
			}

			else if ( Const.PRO_ACTION_YULAN == actStatus ) {
				
			}
			else if ( Const.PRO_ACTION_OUT == actStatus ) {
				//只更新 下架状态
				Card ocard = sss.getCardById ( id ) ; 
				Byte bos = ocard.getProOnOffStatus ( ) ; 
				if ( !NumberUtils.isEmptyOrZero ( bos ) &&  Const.PRO_PUB_STATUS_PUBED == bos.byteValue ( )   ) {
					ocard.setProOnOffStatus ( Const.PRO_PUB_STATUS_PUB_OUT ) ; 
					sss.updateCard ( ocard ) ; 									
				}
			}		
			//save content
			if ( Const.PRO_ACTION_SUB == actStatus || Const.PRO_ACTION_SUB_PUB == actStatus ) { 
				ProContent content = new ProContent( Byte.valueOf ( Const.PRO_TYPE_CART ) , id )  ; 
				content.setContent ( cardForm.getContent ( ) ) ; 
				proContentServiceImpl.saveAndUpdateProContent ( content ) ;		
			}
		}
		return new ActionForward( "card.go?method=getCard&proId=" + id , true ); 
	}	
	
	public  ActionForward removeCard ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//PARAMS
		CardForm cardForm = ( CardForm ) form ; 
		Byte actStatus = cardForm.getProActStatus ( ) ;
		Date offTime = cardForm.getOffTime ( ) ; 
		//BIS
		CardServiceImpl sss = ( CardServiceImpl )getBean ( "cardServiceImpl" ) ;
		
		Long[] deleteIds = cardForm.getDeleteId ( ) ;
		if ( deleteIds != null ) {
			for ( Long deleteId : deleteIds ) {
				Card card = sss.getCardById ( deleteId ) ;
				Byte bos = card.getProOnOffStatus ( ) ; 
				if ( Const.PRO_ACTION_PUB == actStatus ) {
					if ( ! NumberUtils.isEmptyOrZero ( bos )
							&& Const.PRO_PUB_STATUS_PUBED != bos.byteValue ( ) ) {
						if ( offTime == null
								|| ( offTime != null && ( new Date ( )
										.getTime ( )- offTime.getTime ( ) < 0 ) ) ) {
							card.setProOnOffStatus ( Const.PRO_PUB_STATUS_PUBED ) ; 
							card.setOffTime ( offTime ) ;
							sss.updateCard (  card ) ; 
						}
					}
				}
				else if ( Const.PRO_ACTION_OUT == actStatus ) { 
					if ( ! NumberUtils.isEmptyOrZero ( bos )
							&& Const.PRO_PUB_STATUS_PUBED == bos.byteValue ( ) ) {					
						card.setProOnOffStatus ( Const.PRO_PUB_STATUS_PUB_OUT ) ;  
						sss.updateCard (  card ) ; 
					}
				}
				else { //delete
					/*
					card.setProOnOffStatus ( Const.PRO_PUB_STATUS_PUB_OUT ) ; 
					card.setRemoveMark ( String.valueOf ( Const.COMMON_REMOVE_MARK_Y ) ) ; 
					sss.updateCard (  card ) ;*/ 
					sss.removeCard ( deleteId ) ; 
				}
				
			}
		}
		return new ActionForward( "card.go?method=getCard" , true ); 
	}	
	

	private Long saveAndUpdateCard( Card cardVo , FormFile formFile  , CardServiceImpl cardService , HttpServletRequest request ) throws Exception {
		Long proId = cardVo.getProId ( ) ; 
		String uploadFn = formFile.getFileName ( ); 
		if ( !StringUtils.isEmpty ( uploadFn ) && !StringUtils.isBlank ( uploadFn ) )   {
			FileUploadUtil upload = new FileUploadUtil( ) ; 
			ThreadSynchronizer.threadEnter ( );
			try {
				upload.setRestrictfs ( 102400 * 5 ) ;
				String fn = upload.uploadv2 ( formFile , request , Const.PRO_CARD_IMG_UPLOAD_PATH , UUID.randomUUID ( ).toString ( ) );
				fn = Const.PRO_CARD_IMG_UPLOAD_PATH + fn;
				cardVo.setCardImg ( fn ) ; 
				//cardService.updateCard (  cardVo );				
			} finally {
				ThreadSynchronizer.threadExit ( );
			}						
		}
		
		if ( !NumberUtils.isEmptyOrZero ( proId )  ) { // update
			Card card = cardService.getCardById ( proId ) ; 
			String cardImg = card.getCardImg ( ) ; 
			if ( StringUtils.isEmpty ( uploadFn ) || StringUtils.isBlank ( uploadFn ) ) 
				cardVo.setCardImg ( cardImg ) ; 
			else {
				FileUploadUtil.removeRealPathFile ( cardImg , request ) ;
			}
			cardService.updateCard ( cardVo ) ;	
		}
		else { //save
			proId = cardService.saveCard ( cardVo ) ; 
		}
		
		//upload

		return proId ; 
	}
	
	/////////////////////////////////////////////////////////////////////////////////////
	
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward getCard4View ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//PARAMS
		CardForm cardForm = ( CardForm ) form ; 
		cardForm.setPageSize ( Const.PAGE_SIZE_Q ) ;
		List< BizOption >  bssOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_TYPE ,  false  , getSessionLanguage( request )  ) ;
		request.setAttribute ( "bssOps" , bssOps ) ;
		
		List< BizOption >  bsspOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_SERVICE_PLAN ,  false  , getSessionLanguage( request )  ) ;
		request.setAttribute ( "bsspOps" , bsspOps ) ;

		SupplierServiceImpl ssbean = ( SupplierServiceImpl )getBean ( "supplierServiceImpl" ) ;
		ProSuppliers psvo = new ProSuppliers( ) ; 
		psvo.setSupplierPros ( StringPool.COMMA + Const.PRO_TYPE_CART + StringPool.COMMA ) ; 
		psvo.setWorkFlg ( String.valueOf ( Const.COMMON_STATUS_ENA ) ) ;
		List< ProSuppliers > proTypes = ssbean.querySuppliersList ( psvo ) ; 
		request.setAttribute ( "proTypes" , proTypes ) ;
		
		CardServiceImpl sss = ( CardServiceImpl )getBean ( "cardServiceImpl" ) ;
		
		Card card = new Card( ) ; 
		PropertyUtils.copyProperties ( card , cardForm ) ; 
		DataList dl =  sss.getCards4View ( card ) ;  
		List< Card > cards =  dl.getNowlist ( ) ;
		CardType cardTypeVo = null;
		CardServicePlan cardServicePlanv = null;
		for ( Card cardTmp : cards ) {
			cardTmp.setCardTypev ( null ) ; 
			cardTmp.setCardServicePlanv ( null ) ; 
			for ( BizOption bioCt : bssOps ) {
				if ( Byte.valueOf ( bioCt.getOptionValue ( ) ) .equals ( 
						cardTmp.getCardType ( ) ) ) {
					cardTypeVo = new CardType ( );
					cardTypeVo.setCardTypeId ( Byte.valueOf ( bioCt
							.getOptionValue ( ) ) );
					cardTypeVo.setCardTypeName ( bioCt.getOptionName ( ) );
					cardTmp.setCardTypev ( cardTypeVo );
					break;
				}
			}
			
			for ( BizOption bizop : bsspOps ) {
				if (  Byte.valueOf (  bizop.getOptionValue ( ) ) .equals ( 
						cardTmp.getCardPlan ( ) ) ) {
					cardServicePlanv = new CardServicePlan ( );
					cardServicePlanv.setCardServicePlanId ( Byte
							.valueOf ( bizop.getOptionValue ( ) ) );
					cardServicePlanv.setCardServicePlanName ( bizop
							.getOptionName ( ) );
					cardTmp.setCardServicePlanv ( cardServicePlanv );
					break;
				}
			}
		}
		request.setAttribute ( "cards" , dl ) ; 
		return mapping.findForward ( "cards4view" ) ; 
	}
	
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward getCardInfo4View ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		long ct = System.currentTimeMillis ( ) ; 
		//DIC
		List< BizOption >  bssOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_TYPE ,  false  , getSessionLanguage( request )  ) ;
		List< BizOption >  bsspOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_B_PRO_CARD_SERVICE_PLAN ,  false  , getSessionLanguage( request )  ) ;
		
		//PARAMS
		CardForm cardForm = ( CardForm ) form ;
		Card card = new Card( ) ; 
		PropertyUtils.copyProperties ( card , cardForm ) ; 

		String flg4boc = cardForm.getFlg4boc ( ) ; 
		
		boolean showModal = false ;
		if ( card.getShowModal ( ) != null
				&& card.getShowModal ( ) )
			showModal = true ; 

		
		Long proId = card.getProId ( ) ;
		
		//
	
		if ( NumberUtils.isEmptyOrZero(  proId) ) {
			return PorJsonObj.response ( response , PorJsonObj.error (
					CONST.COUNTRY_ZH ).toString ( ) );
		}
		ProContentServiceImpl proContentServiceImpl = ( ProContentServiceImpl )getBean( "proContentServiceImpl" ) ; 		
		CardServiceImpl sss = ( CardServiceImpl )getBean ( "cardServiceImpl" ) ;
		
		if ( Const.FLG_FOR_GET_BASEINFO.equals ( flg4boc ) ) { 
			if ( showModal ) 
				card = sss.getCardById ( proId ) ; 
			else 
				card = sss.getBaseCardById4View ( proId ) ; 
			
			if ( card == null ) 
				return mapping.findForward ( "proout" );
		
			CardType cardTypeVo = null;
			CardServicePlan cardServicePlanv = null;		
			card.setCardTypev ( null ) ; 
			card.setCardServicePlanv ( null ) ; 
			for ( BizOption bioCt : bssOps ) {
				if ( Byte.valueOf ( bioCt.getOptionValue ( ) ) .equals ( 
						card.getCardType ( ) ) ) {
					cardTypeVo = new CardType ( );
					cardTypeVo.setCardTypeId ( Byte.valueOf ( bioCt
							.getOptionValue ( ) ) );
					cardTypeVo.setCardTypeName ( bioCt.getOptionName ( ) );
					card.setCardTypev ( cardTypeVo );
					break;
				}
			}		
			
			for ( BizOption bizop : bsspOps ) {
				if (  Byte.valueOf (  bizop.getOptionValue ( ) ) .equals ( 
						card.getCardPlan ( ) ) ) {
					cardServicePlanv = new CardServicePlan ( );
					cardServicePlanv.setCardServicePlanId ( Byte
							.valueOf ( bizop.getOptionValue ( ) ) );
					cardServicePlanv.setCardServicePlanName ( bizop
							.getOptionName ( ) );
					card.setCardServicePlanv ( cardServicePlanv );
					break;
				}
			}			
			request.setAttribute ( "vo" , card ) ; 
			return mapping.findForward ( "card4view" ) ;
		}
		
		logger.info ( "card4View.." + ( System.currentTimeMillis ( ) - ct ) ) ; 
		
		if ( Const.FLG_FOR_GET_CONTENTINFO.equals ( flg4boc ) ) { 
			ProContent pcontent = proContentServiceImpl.getProContentCacheModel (  
					new ProContent( Byte.valueOf ( Const.PRO_TYPE_CART ) ,  proId  )  ) ;
			if ( pcontent != null ) 
				return PorJsonObj.response ( response , PorJsonObj
						.getProContentJSONObject ( pcontent.getContent ( ) ).toString ( ) );
			else 
				return PorJsonObj.response ( response , PorJsonObj
						.getProContentJSONObject ( "" ).toString ( ) );

		}


	
		return PorJsonObj.response ( response , PorJsonObj.error (
				CONST.COUNTRY_ZH ).toString ( ) );

	}
	
}
